<template>
  <div class="pay">
    <van-nav-bar fixed title="订单结算台" left-arrow @click-left="$router.go(-1)" />

    <!-- 地址相关 -->
    <div class="address" v-if="status === 1">

      <div class="left-icon">
        <van-icon name="logistics" />
      </div>

      <div class="info" v-if="true">
        <div class="info-content">
          <span class="name">{{ address.name }}</span>
          <span class="mobile">{{ address.tel }}</span>
        </div>
        <div class="info-address">
          {{ address.address }}
        </div>
      </div>

      <div class="info" v-else @click="goAddressBook">
        请选择配送地址
      </div>

      <div class="right-icon" @click="goAddressBook">
        <van-icon name="arrow" />
      </div>
    </div>

    <!-- 订单明细 -->
    <div class="pay-list">
      <div class="list">
        <div class="goods-item" v-for="(goods, index) in cartList" :key="index">
          <div class="dish" v-if="goods.item.dishBasicDto !== null">
            <div class="left">
              <img :src="goods.item.dishBasicDto.image" alt="" />
            </div>
            <div class="right">
              <p class="tit text-ellipsis-2">
                {{ goods.item.dishBasicDto.dishName }}&nbsp;{{ goods.item.dishBasicDto.description }}
              </p>
              <p class="info">
                <span class="count">x{{ goods.item.num }}</span>
                <span class="price">¥{{ goods.item.totalMoney * goods.item.num }}</span>
              </p>
              <p>{{ goods.item.flavorString }}</p>
            </div>
          </div>
          <div class="setmeal" v-if="goods.item.setmealBasicDto !== null">
            <div class="left">
              <img :src="goods.item.setmealBasicDto.image" alt="" />
            </div>
            <div class="right">
              <p class="tit text-ellipsis-2">
                {{ goods.item.setmealBasicDto.setmealName }}&nbsp;{{ goods.item.setmealBasicDto.description }}
              </p>
              <p class="info">
                <span class="count">x{{ goods.item.num }}</span>
                <span class="price">¥{{ goods.item.totalMoney * goods.item.num}}</span>
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="flow-num-box">
        <span>共 {{ selCount }} 件商品，合计：</span>
        <span class="money">￥{{ selPrice }}</span>
      </div>

      <div class="pay-detail">
        <div class="pay-cell">
          <span>订单总金额：</span>
          <span class="red">￥{{ selPrice }}</span>
        </div>

        <div class="pay-cell">
          <span>优惠券：</span>
          <span>无优惠券可用</span>
        </div>

        <div class="pay-cell">
          <span>餐具数量：</span>
          <span>商家按餐量提供</span>
        </div>

        <div class="pay-cell" v-if="status === 1">
          <span>配送费用：</span>
          <span v-if="false">请先选择配送地址</span>
          <span v-else class="red">+￥6.00</span>
        </div>
      </div>

      <!-- 买家留言 -->
      <div class="buytips">
        <textarea placeholder="选填：买家留言（50字内）" name="" id="" cols="30" rows="10"
          v-model="orderBasic.userText"></textarea>
      </div>
    </div>

    <!-- 底部提交 -->
    <div class="footer-fixed">
      <div class="left">实付款：<span>￥{{ totalMoney }}</span></div>
      <div class="tipsbtn" @click="submitOrder">提交订单</div>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'PayIndex',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      status: 1,
      baseAddress: '/address-book',
      baseOrder: '/order-basic',
      addressList: [],
      address: {},
      totalMoney: 0,
      orderBasic: {
        id: 0,
        addressId: 0,
        totalMoney: 0,
        orderDetail: '',
        userText: ''
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapState('cart', ['cartList']),
    ...mapGetters('cart', ['cartTotal', 'selCount', 'selPrice', 'isAllChecked'])
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 获取当前用户的地址列表
    async getaddressList () {
      await request({
        url: this.baseAddress + '/address-list',
        method: 'get'
      }).then(res => {
        const data = res.data.data
        this.transform(data)
        this.address = this.addressList[0]
        this.orderBasic.addressId = this.address.id
      })
    },
    // 不同名称字段数据转化
    transform (data) {
      const addressList = []
      data.forEach(item => {
        const address = {
          id: 0,
          name: '',
          tel: '',
          address: '',
          isDefault: false
        }
        address.id = item.id
        address.name = item.name
        address.tel = item.phone
        address.address = item.provinceName + item.cityName + item.districtName + ' ' + item.detail
        address.isDefault = item.isDefault
        addressList.push(address)
      })
      this.addressList = addressList
    },
    // 跳转到地址簿
    goAddressBook () {
      this.$router.push({
        name: 'AddressBook',
        query: {
          backUrl: '/pay'
        }
      })
    },
    // 提交订单
    async submitOrder () {
      if (this.status === 1) {
        this.orderBasic.totalMoney = this.totalMoney
      } else {
        this.orderBasic.addressId = 0
      }
      await request({
        url: this.baseOrder + '/order-basic',
        method: 'post',
        data: this.orderBasic
      }).then(res => {
        if (res.data.data) {
          // 清除购物车中已付款的数据
          if (this.selCount === 0) return
          this.$store.dispatch('cart/delSelect')
          this.isEdit = false
          this.$router.push({
            name: 'PaySuccess'
          })
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    if (typeof this.$route.params.status !== 'undefined') {
      this.status = this.$route.params.status
      if (this.status === 1) {
        this.totalMoney = 6 + Number(this.selPrice)
        this.totalMoney = Math.round(this.totalMoney * 100) / 100
        this.orderBasic.totalMoney = this.selPrice
      } else {
        this.totalMoney = this.selPrice
        this.orderBasic.totalMoney = this.selPrice
      }
    }
    if (typeof this.$route.query.address !== 'undefined') {
      this.address = this.$route.query.address
      this.orderBasic.addressId = this.address.id
    } else {
      this.getaddressList()
    }
    this.orderBasic.orderDetail = JSON.stringify(this.cartList)
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.pay {
  padding-top: 46px;
  padding-bottom: 46px;
  ::v-deep {
    .van-nav-bar__arrow {
      color: #333;
    }
  }
}
.address {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  font-size: 14px;
  color: #666;
  position: relative;
  background: url(@/assets/border-line.png) bottom repeat-x;
  background-size: 60px auto;
  .left-icon {
    margin-right: 20px;
  }
  .right-icon {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-7px);
  }
}
.goods-item {
  .dish,.setmeal {
    height: 100px;
    margin-bottom: 6px;
    padding: 10px;
    background-color: #fff;
    display: flex;

    .left {
    width: 100px;
      img {
        display: block;
        width: 80px;
        margin: 10px auto;
      }
    }
  }
  .right {
    flex: 1;
    font-size: 14px;
    line-height: 1.3;
    padding: 10px;
    padding-right: 0px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    color: #333;
    .info {
      margin-top: 5px;
      display: flex;
      justify-content: space-between;
      .price {
        color: #fa2209;
      }
    }
  }
}

.flow-num-box {
  display: flex;
  justify-content: flex-end;
  padding: 10px 10px;
  font-size: 14px;
  border-bottom: 1px solid #efefef;
  .money {
    color: #fa2209;
  }
}

.pay-cell {
  font-size: 14px;
  padding: 10px 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
  .red {
    color: #fa2209;
  }
}
.pay-detail {
  border-bottom: 1px solid #efefef;
}

.pay-way {
  font-size: 14px;
  padding: 10px 12px;
  border-bottom: 1px solid #efefef;
  color: #333;
  .tit {
    line-height: 30px;
  }
  .pay-cell {
    padding: 10px 0;
  }
  .van-icon {
    font-size: 20px;
    margin-right: 5px;
  }
}

.buytips {
  display: block;
  textarea {
    display: block;
    width: 100%;
    border: none;
    font-size: 14px;
    padding: 12px;
    height: 100px;
  }
}

.footer-fixed {
  position: fixed;
  background-color: #fff;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 46px;
  line-height: 46px;
  border-top: 1px solid #efefef;
  font-size: 14px;
  display: flex;
  .left {
    flex: 1;
    padding-left: 12px;
    color: #666;
    span {
      color:#fa2209;
    }
  }
  .tipsbtn {
    width: 121px;
    background: linear-gradient(90deg,#f9211c,#ff6335);
    color: #fff;
    text-align: center;
    line-height: 46px;
    display: block;
    font-size: 14px;
  }
}
</style>
